<style>
  #app{display: table;width:100%;}

 .register .main-title{text-align: center;font-size:16px;font-weight: normal;margin-bottom: 20px;}
.register  .des{text-align: center;color:#999;margin-bottom: 2em;}
 .register .login-form{width:300px;margin:0 auto;}
.register .login-page{width:600px;height:520px;margin:0 auto; padding: 10px 0;
    border-radius: 8px;
    background: #fff;}

.register  .login_main{    height: 99.8vh;   background: #f7f7f7;
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
    -webkit-box-orient: vertical;
    -webkit-box-direction: normal;
    -ms-flex-direction: column;
    flex-direction: column;}
.register .login_content{    width: 100%;
    height: 100%;
    position: relative;
    z-index: 1;
    display: flex;

    align-items: center;

    justify-content: center;}
.register .login_content .el-select{width:100%;}
#code{
    font-size: 18px;
    letter-spacing:3px;
    color: #053d84;
    background: #f2f2f5;
}
.register .verify .el-form-item__content{display: flex;align-items: center;}
/*.verify .el-form-item__content>div{width:33.33%;}*/
.register .verify .el-input .el-input__inner{width:140px;}
.register .forget{    background-color: hsla(0,87%,69%,.1);padding:0 10px;    border-radius: 4px;
    box-sizing: border-box;font-size: 12px;height:32px;line-height: 32px;display: inline-block;
    border: 1px solid rgba(64,158,255,.2);
    border-color: hsla(0,87%,69%,.2);
    color: #f56c6c;}
.register .forget a{color:#7e8c8d;}
.register .verification1{display: flex;}
.register .verification1.el-button{border-radius: 0 4px 4px 0;background: #f5f7fa;color:#909399;font-size:14px;width: 112px;   box-sizing: border-box; padding: 12px 9px;}
.register .verification1.el-button .span_padding{
  padding:0 11px;
}
.register .verify .phoneVerify .el-input__inner{width:100%;border-radius: 4px 0 0 4px;}
.register .el-checkbox-group {text-align: center;}
.register .btn_reg{margin-bottom: 10px;}
.register .service{color:#178fe3;}
</style>
<template>
  <div class="register">
    <div class="login_main">
      <div class="header_index">
        <myHeader></myHeader>

      </div>
      <div class="login_content">     

        <div class="g-center login-page" @keyup.enter="register">
          <el-form :model="regForm" class="login-form" :rules="regFormRules" ref="regForm">
            <h1 class="main-title">欢迎注册</h1>
             
            <el-form-item  prop="mobile">
              <el-input
                :autofocus="true"
                placeholder="请输入手机账号"  @blur="isRegMobile"
                v-model="regForm.mobile">
              </el-input>
            </el-form-item>
             <el-form-item  prop="password">
              <el-input
                type="password"
                :autofocus="true"
                placeholder="设置登录密码" 
                v-model="regForm.password">
              </el-input>
            </el-form-item>
            <el-form-item prop="repassword">
              <el-input
                placeholder="重复输入密码" 
                type="password"
                v-model="regForm.repassword">
              </el-input>
            </el-form-item>
   
            <el-form-item class="verify" prop="verifycode">
              <el-input type="text" placeholder="请输入验证码" v-model="regForm.verifycode" class="yanzhengma_input" @blur.native="checkLpicma"></el-input>
              <el-input type="button" id="code" @click.native="createCode" class="verification1" v-model="regForm.checkCode"></el-input>
            </el-form-item>
            <el-form-item class="verify" prop="mobileCode">
              <el-input type="text" placeholder="请输入手机验证码" class="phoneVerify" v-model="regForm.mobileCode"></el-input>
              <el-button v-if="!isSendVerify" @click.native="sendVerify" type="default" class="verification1"><span class="span_padding">发送验证码</span></el-button>
              <el-button v-if="isSendVerify" type="default" class="verification1">{{time}}s后重新发送</el-button>

            </el-form-item>
             <el-form-item >
              <el-input type="text" placeholder="请输入邀请码(选填)" v-model="regForm.invitation"></el-input>
            </el-form-item>
            <el-form-item class="btn_reg">
              <el-button style="width:100%"  @click.native="register" type="primary" :loading="isBtnLoading">{{btnText}}</el-button>
            </el-form-item>
            <el-form-item >
              <el-checkbox-group v-model="regForm.type">
                <el-checkbox label="阅读并同意" name="type">                
                  <span>阅读并同意</span>
                  <router-link class="service" to="/service">《用户服务协议》</router-link>
              </el-checkbox>              
              </el-checkbox-group>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>
   
  </div>
</template>

<script>
import instance from '../api';
import isvalidPhone from '../api/valide';
import * as common from '../api/common';

import axios from 'axios';
import CryptoJS from "crypto-js";
import * as util from '../assets/util.js';
import * as login from '../api/login.js';
 import cookie from '../api/cookie.js'
import md5 from 'js-md5';
import myHeader from './common/header'


var code ; //在全局定义验证码
export default {
  components:{
    myHeader
  },
  data() {
    var validPhone=(rule, value,callback)=>{
      if (!value){
          callback(new Error('请输入电话号码'))
      }else  if (!isvalidPhone.isvalidPhone(value)){
        callback(new Error('请输入正确的11位手机号码'))
      }else{
        // console.log(this.isRegMobile())
        // callback(new Error('该号码已经注册过'))    
        // this.isRegMobile()     
          callback();
          
      }
    };
    var validatePass = (rule, value, callback) => {   
      if (value === '') {
          callback(new Error('请再次输入密码'));
        } else if (value !== this.regForm.password) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
    };
    var validateVerify = (rule, value, callback) => {   
      if (value === '') {
          callback(new Error('请输入验证码'));
        } else if (value !== this.regForm.checkCode.toLowerCase()) {
          callback(new Error('验证码输入错误'));
        } else {
          callback();
        }
    };
    return {
      time:60,
      regFormRules:{
        mobile: [
            // { required: true, message: '请输入手机号', trigger: 'blur' }
            { required: true, trigger: 'blur', validator:validPhone }//这里需要用到全局变量

          ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ],
        repassword:[
          { required: true, trigger: 'blur', validator:validatePass }//这里需要用到全局变量

        ],
        verifycode:[
          { required: true, validator:validateVerify, trigger: 'blur' }

        ],
        mobileCode:[
          { required: true, message: '请再输入手机验证码', trigger: 'blur' }

        ],
      },
      /*picLyanzhengma:'',
      checkCode:'',*/
      regForm:{region:'china',checkCode:'',verifycode:'',type:true,password:'',invitation:''},
     /* username: '',
      password: '',*/
      isBtnLoading: false,
      isSendVerify:false,
      isreg:true,
    };
  },
  computed: {
    btnText() {
      if (this.isBtnLoading) return '注册中...';
      return '同意条款并注册';
    }
  },
  methods: {

      // 图片验证码
    createCode(){
      console.log("aaa")
      code = "";

      var codeLength =
      4;//验证码的长度 

      var random =
      new Array(0,1,2,3,4,5,6,7,8,9,'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R',

      'S','T','U','V','W','X','Y','Z');//随机数

      for(var
      i = 0; 
      i < codeLength; 
      i++) {//循环操作 

      var index =
      Math.floor(Math.random()*36);//取得随机数的索引（0~35）

      code += random[index];//根据索引取得随机数加到code上

      } 

      this.regForm.checkCode =
      code;//把code值赋给验证码

    },

      // 失焦验证图和密码

    checkLpicma(){


      this.regForm.verifycode.toUpperCase();//取得输入的验证码并转化为大写

      if(this.regForm.verifycode ==
      '') {

      $(".login_content1 span:eq(2)").text("请输入验证码")

      $(".login_content1 span:eq(2)").removeClass("disappear");


      }else if(this.regForm.verifycode.toUpperCase() !=
      this.regForm.checkCode ) {
      //若输入的验证码与产生的验证码不一致时 

      console.log(
      this.regForm.verifycode.toUpperCase())

      console.log(code)

      $(".login_content1 span:eq(2)").text("验证码不正确")

      $(".login_content1 span:eq(2)").removeClass("disappear");

      this.createCode();//刷新验证码

      this.regForm.verifycode =
      '';

      }else { //输入正确时

        alert("验证码正确")

        $(".login_content1 span:eq(2)").addClass("disappear");

        $(".login_content1 span:eq(2)").text("请输入验证码")

        return true;
      }

    },
    isRegMobile(){
      // let isreg=true;
      if(this.regForm.mobile){
        let para={
          mobile:this.regForm.mobile
        }
        common.validMobileReg.r(para).then((res)=>{
            console.log(res);
            if(res.data.retCode==1){
              if(res.data.data!=null&&res.data.data!='null'&&res.data.data!=''){
                this.isreg= true;
                // callback();
                 this.$message.error('该号码已经注册过')
              }else{
                this.isreg= false;               

              }
            }else{
              this.$message.error(res.data.retMsg)
                this.isreg= true;              
            }

          })
      }
   
    },
    sendVerify(){
      if(this.regForm.mobile){
        if(this.isreg){
          this.$message.error("该号码已经注册过");
          return;
        }
        let para={
          mobile:this.regForm.mobile,
          verifyCode:this.regForm.verifycode
        }
        console.log(para)
        common.sendVerify.r(para).then((res)=>{
          console.log(res);
          if(res.data.retCode==1){
            this.$message.success("验证码发送成功")
            this.isSendVerify=true;
            let vm=this;
            let interval = setInterval(function() {
            if ((vm.time--) <= 0) {
              vm.time = 60;
              vm.isSendVerify = false;
              clearInterval(interval);
             }
            }, 1000);
          }else{
            this.$message(res.data.retMsg);
          }
        })
      }
     
    },

    register() {
      console.log(this.isreg)
      var vm = this;
      this.$refs.regForm.validate((valid) => {
        if (valid) {
          if(!this.regForm.type){
            this.$message.error("请选择同意服务协议");
            return;
          }
         /* if(!this.isSendVerify){
            this.$message.error("请发送手机验证码");
            return;
          }*/
          if(this.isreg){
             this.$message.error("该号码已经注册过");
            return;
          }
          let para={
            mobile:this.regForm.mobile,
            password:md5('STARSAND_' + this.regForm.password),
            mobileCode:this.regForm.mobileCode,
            invitionCode:this.regForm.invitation
          }
          console.log(para);
          common.register.r(para).then((res)=>{
            console.log(res);
            if(res.data.retCode==1){
              sessionStorage.setItem('userId',res.data.data.userId);
              // sessionStorage.setItem('userId','152473775467100000')
               sessionStorage.setItem('islogin',"login");


              this.$router.push('/personalcenter');
            }else{
              this.$message.error(res.data.retMsg)
            }
          })
        }else{
          console.log('error submit!!');
          return false;
        }

      })


    }
  },
  created() {
    sessionStorage.clear();
    sessionStorage.setItem('activeIndex','login');
    cookie.logout('merchant_token');
    
    this.createCode();
  }
};
</script>
